package com.happy_hao.topbiz.service.impl;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.happy_hao.topbiz.config.FeishuConfig;
import com.happy_hao.topbiz.exception.ServiceException;
import com.happy_hao.topbiz.service.Oauth2Service;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import java.util.HashMap;
import java.util.Map;

@Service
public class Oauth2ServiceImpl implements Oauth2Service {

    @Resource
    private FeishuConfig feishuConfig;

    @Override
    public String getPhoneByCode(String code, boolean mod) {
        return getPhoneByToken(getTokenByCode(code, mod));
    }

    private String getTokenByCode(String code, boolean mod) {
        Map<String, Object> params = new HashMap<>();
        params.put("grant_type", "authorization_code");
        params.put("client_id", feishuConfig.getClientId());
        params.put("client_secret", feishuConfig.getClientSecret());
        params.put("code", code);
        if (mod) {
            params.put("redirect_uri", feishuConfig.getRedirectUri1());
        } else {
            params.put("redirect_uri", feishuConfig.getRedirectUri2());
        }


        String result = HttpUtil.createPost(feishuConfig.getTokenUri())
                .header("Content-Type", "application/json")
                .charset("utf-8")
                .body(JSONUtil.toJsonStr(params))
                .execute()
                .body();

        if (!StringUtils.hasText(result)) {
            throw new ServiceException("获取飞书 token 失败，响应为空");
        }

        JSONObject parseObj = JSONUtil.parseObj(result);
        if ((int) parseObj.get("code") != 0) {
            throw new ServiceException("请求飞书 token 失败：" + parseObj.get("error_description"));
        }

        String userAccessToken = parseObj.getStr("access_token");
        String tokenType = parseObj.getStr("token_type");

        return tokenType + " " + userAccessToken;
    }

    private String getPhoneByToken(String token) {
        String result = HttpUtil.createGet(feishuConfig.getUserInfoUri())
                .header("Authorization", token)
                .header("Content-Type", "application/json")
                .charset("utf-8")
                .execute()
                .body();

        if (!StringUtils.hasText(result)) {
            throw new ServiceException("请求飞书用户详情接口失败，响应为空");
        }

        JSONObject parseObj = JSONUtil.parseObj(result);
        return parseObj.getStr("mobile").replace("+86", "");
    }
}
